package logic

import (
	"context"
	"fmt"
	"person/cache"
	"person/model"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *personrpc.LoginRequest) (*personrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var person model.Person
	model.DB.Debug().Where("tel=?", in.Tel).Find(&person)
	if person.ID == 0 {
		return nil, fmt.Errorf("该用户未注册")
	}
	c, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Tel).Result()
	if c != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误")
	}
	return &personrpc.LoginResponse{
		Id: int64(person.ID),
	}, nil
}
